import javax.swing.table.AbstractTableModel;

import resources.InvalidExpressionException;
import resources.NoSuchVariableExistsException;
import resources.Tools;
import resources.VariableAssignmentException;

/**
 * ValTable.java - This class extends AbstractTableModel and sets up the underlying structure
 * of ValTable, it takes a value from the cell in FormTable, and tries to compute and place
 * the outcome into the respective cell in itself.
 *   
 * @author Andrew Gifford, Marc Vandehey
 */
@SuppressWarnings("serial")
public class ValTable extends AbstractTableModel{

	/**
	 * Accesses for the maximum column count from FormTable
	 * 
	 * @return MAX column count
	 */
	public int getColumnCount(){
		return FormTable.MAX;
	}
	
	/**
	 * Accesses for the maximum row count from FormTable
	 * 
	 * @return MAX row count
	 */
	public int getRowCount(){
		return FormTable.MAX;
	}

	/**
	 * Accesses the value at a specified row and column, and tries to compute it.
	 * Throws Errors when it is a Bad Expression, Reference Error, and Bad Variable
	 * 
	 * @param row	Row represented as an Integer
	 * @param column	column represented as an Integer
	 * @return the object at the specified row and column
	 */
	public Object getValueAt(int row, int column) {
		
		String cellName = this.getColumnName(column) + row;
		Frame.setErrorFalse(-1);
		try {
			return Tools.getEvaluator(cellName).evaluate(cellName).toString();
		} catch (NoSuchVariableExistsException e) {
			return "";
		} catch (InvalidExpressionException e) {
			Frame.setErrorTrue(row);
			return "#BAD-EXPRESSION!";
		} catch (VariableAssignmentException e) {
			Frame.setErrorTrue(row);
			return "#BAD-VAR!";
		} catch (java.lang.IndexOutOfBoundsException e){
			if (Frame.formTable.getValueAt(row,column).equals(""))
				return "";
			else
				Frame.setErrorTrue(row);
				return "#BAD-VAR!";
		} catch (java.lang.StackOverflowError e){
			Frame.setErrorTrue(row);
			return "#REF-ERROR!";
		}		
	}
}
